const {
	Service
} = require("uni-cloud-router");
const {
	result_success,
	result_error
} = require('http-result-modle')
const db = uniCloud.database()
module.exports = class OrderSyncService extends(
	Service
) {
	/**
	 * 支付宝执行同步
	 */
	async alipayExec(order) {
		let biz_content = {
			out_biz_no: order._id,
			buyer_id: order.openid,
			order_type: "SERVICE_ORDER",
			trade_no: order.alipay_trade_no,
			trade_type: "TRADE",
			send_msg: "N",
			// item_order_list: this.createIOL(order.items[0].order_content),
			ext_info: [ {
				"ext_key": "business_info",
				"ext_value": "{'rebate_pid':'2088331963340633'}"
			}],
			"shop_info": {
				"merchant_shop_id": order.alipay_shop_id
			},
		}
		if (order.discounts_price) {
			if (order.actually_shop_income < order.total_price) {
				biz_content.amount = order.actually_shop_income / 100 - order.discounts_price / 100
				biz_content.pay_amount = order.actually_shop_income / 100
				biz_content.discount_amount = order.discounts_price / 100
			} else {
				biz_content.amount = order.actually_shop_income / 100
				biz_content.pay_amount = order.actually_shop_income / 100
				biz_content.discount_amount = 0
			}
		} else {
			biz_content.amount = order.actually_shop_income / 100
			biz_content.pay_amount = order.actually_shop_income / 100
			biz_content.discount_amount = 0
		}
		let syncData = {
			creator_id: order.creator_id,
			creator_name: order.creator_name,
			create_time: new Date().getTime(),
			app_id: order.app_id,
			shop_id: order.shop_id,
			order_id: order._id,
			alipay_id: order.alipayId,
			alipay_isv_pid: order.alipayIsvpId,
			alipay_shop_id: order.alipay_shop_id,
			buyer_id: order.openid,
			trade_no: order.alipay_trade_no,
			order_sync_data: biz_content,
			order_sync_status: 0
		}
		await db.collection('log-alipay-order-sync').add(syncData)
		if (!order.alipay_shop_id) {
			await db.collection('log-alipay-order-sync').where({
				order_id: order._id
			}).update({
				order_sync_status: 2,
				order_sync_reason: "未填写门店ID"
			})
			return result_error("未填写门店ID")
		}
		let orderSync = await alipayRequestCommon(order.app_id, 'alipay.merchant.order.sync', biz_content)
		if (orderSync.data.code === "10000") {
			await db.collection('log-alipay-order-sync').where({
				order_id: order._id
			}).update({
				order_sync_status: 1,
				order_sync_reason: orderSync.data
			})
			return result_success()
		} else {
			await db.collection('log-alipay-order-sync').where({
				order_id: order._id
			}).update({
				order_sync_status: 2,
				order_sync_reason: orderSync.data
			})
			return result_error(orderSync.data.sub_msg)
		}
	}
};
